#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QFile>
#include "ApplyDelegate.h"
#include <QFileDialog>
#include <QDir>
#include "DataFilterDialog.h"
#include "descrypt.h"
#include <QtXlsx>
#include "xlsxdocument.h"
#include "xlsxformat.h"
#include "xlsxcellrange.h"
#include "xlsxchart.h"
#include "zint.h"
#include "qzint.h"
#include <QPrinter>
#include <QPrintPreviewDialog>
#include "printerdialog.h"

QTXLSX_USE_NAMESPACE
using namespace Zint;
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    isAscendingOrder =1;
    /*团号只能是数字*/

    /*设置英文姓和名只能输入字母和数字*/
    QRegExp regx("^[ A-Za-z]*$");
    QValidator *validator = new QRegExpValidator(regx);
    ui->firstNameEdit->setValidator(validator);
    ui->lastNameEdit->setValidator(validator);
    //设置英文姓和名 大写
    connect(ui->firstNameEdit,SIGNAL(editingFinished()),this,SLOT(firstNameEditFinish()));
    connect(ui->lastNameEdit,SIGNAL(editingFinished()),this,SLOT(lastNameEditFinish()));

    /*设置photo名称*/
    ui->photoEdit->setEnabled(false);
    connect(ui->groupEdit,SIGNAL(editingFinished()),this,SLOT(photoNameEditFinish()));
    connect(ui->numEdit,SIGNAL(editingFinished()),this,SLOT(photoNameEditFinish()));
    ui->groupNum1Edit->setEnabled(false);

    //QComboBox 是 edit 状态 需要对输入的文字 进行筛选 如果不在comboBox里面就重置为第一项目
    connect(ui->comboBox, SIGNAL(currentTextChanged(QString)), this, SLOT(comboBoxProcess(QString)));
    connect(ui->comboBox_2, SIGNAL(currentTextChanged(QString)), this, SLOT(comboBoxProcess(QString)));
    connect(ui->comboBox_3, SIGNAL(currentTextChanged(QString)), this, SLOT(comboBoxProcess(QString)));
    connect(ui->comboBox_4, SIGNAL(currentTextChanged(QString)), this, SLOT(comboBoxProcess(QString)));
    connect(ui->comboBox_5, SIGNAL(currentTextChanged(QString)), this, SLOT(comboBoxProcess(QString)));
    connect(ui->comboBox_6, SIGNAL(currentTextChanged(QString)), this, SLOT(comboBoxProcess(QString)));
    connect(ui->comboBox_7, SIGNAL(currentTextChanged(QString)), this, SLOT(comboBoxProcess(QString)));
    connect(ui->comboBox_8, SIGNAL(currentTextChanged(QString)), this, SLOT(comboBoxProcess(QString)));
    connect(ui->comboBox_9, SIGNAL(currentTextChanged(QString)), this, SLOT(comboBoxProcess(QString)));
    connect(ui->comboBox_10, SIGNAL(currentTextChanged(QString)), this, SLOT(comboBoxProcess(QString)));
    connect(ui->comboBox_11, SIGNAL(currentTextChanged(QString)), this, SLOT(comboBoxProcess(QString)));
    connect(ui->comboBox_12, SIGNAL(currentTextChanged(QString)), this, SLOT(comboBoxProcess(QString)));
    connect(ui->comboBox_13, SIGNAL(currentTextChanged(QString)), this, SLOT(comboBoxProcess(QString)));
    connect(ui->comboBox_14, SIGNAL(currentTextChanged(QString)), this, SLOT(comboBoxProcess(QString)));

    //所有的日期控件 日期为当天
    ui->dateEdit->setDate(QDate::currentDate());
    ui->dateEdit_2->setDate(QDate::currentDate());
    ui->dateEdit_3->setDate(QDate::currentDate().addDays(5));
    ui->dateEdit_4->setDate(QDate::currentDate());
    ui->dateEdit_5->setDate(QDate::currentDate());

    //停留天数 停留日期至
    //停留天数只接受从1到30的整数
    QIntValidator *dateValidator = new QIntValidator(0,30,this);
    ui->stayDayEdit->setText("30");
    ui->stayDayEdit->setValidator(dateValidator);
    connect(ui->stayDayEdit,SIGNAL(editingFinished()),this,SLOT(stayDayEditFinish()));

    connect(ui->radioButton, SIGNAL(clicked()), this, SLOT(onRadioClick()));
    connect(ui->radioButton_2, SIGNAL(clicked()), this, SLOT(onRadioClick()));
    emit  ui->radioButton->clicked();

    //序号只接受从1到999的整数
    QIntValidator *numValidator = new QIntValidator(0,999,this);
    ui->numEdit->setValidator(numValidator);
    connect(ui->numEdit,SIGNAL(editingFinished()),this,SLOT(stayDayEditFinish()));

    //团体人数只接受从1到999的整数
    ui->totalNumEdit->setValidator(numValidator);
    connect(ui->totalNumEdit,SIGNAL(editingFinished()),this,SLOT(stayDayEditFinish()));

}

void MainWindow::stayDayEditFinish()
{
    QLineEdit *stayDay = qobject_cast< QLineEdit *>(sender());
    if (sender() == ui->numEdit||sender() == ui->stayDayEdit||sender() == ui->totalNumEdit){
        if(stayDay->text().toInt()<1){
            stayDay->setText("1");
        }
    }
}


bool MainWindow::copyFileToPath(QString sourceDir ,QString toDir, bool coverFileIfExist)
{
    toDir.replace("\\","/");
    if (sourceDir == toDir){
        return true;
    }
    if (!QFile::exists(sourceDir)){
        return false;
    }
    QDir *createfile     = new QDir;
    bool exist = createfile->exists(toDir);
    if (exist){
        if(coverFileIfExist){
            createfile->remove(toDir);
        }
    }//end if

    if(!QFile::copy(sourceDir, toDir))
    {
        return false;
    }
    return true;
}

void MainWindow::createApply()
{
    QString dbName = ui->groupBox_3->title();
    dbName =  dbName.replace(0,3,"");
    QString dirStr = qApp->applicationDirPath()+"/data/"+dbName;
    QDir dir;
    if(!dir.exists(dirStr))//判断需要创建的文件夹是否存在
    {
        dir.mkdir(dirStr); //创建文件夹
    }
    QString fileName = dirStr+"/"+dbName+".txt";
    QFile file( fileName );

    int rows = ui->applyTable->model()->rowCount(); //行总数
    int cols = ui->applyTable->model()->columnCount()-1; //列总数

    if ( file.open( QIODevice::WriteOnly ) ) {//只读模式
        QTextStream stream( &file );
        for(int i=0; i<rows; i++){
            for(int j = 0; j<cols; j++){
                if(j==0)
                    continue;
                if(j==cols-1){
                    stream << this->model->index(i,j).data().toString();
                }else{
                    stream << this->model->index(i,j).data().toString()<< "\t";
                }
            }
            stream<<"\r\n";
        }
    }
    file.close();


    QFileDialog *fileDialog = new QFileDialog(this);//创建一个QFileDialog对象，构造函数中的参数可以有所添加。
    fileDialog->setWindowTitle(tr("Save As"));//设置文件保存对话框的标题
    fileDialog->setAcceptMode(QFileDialog::AcceptSave);//设置文件对话框为保存模式
    fileDialog->setFileMode(QFileDialog::AnyFile);//设置文件对话框弹出的时候显示任何文件，不论是文件夹还是文件
    fileDialog->setViewMode(QFileDialog::Detail);//文件以详细的形式显示，显示文件名，大小，创建日期等信息；

    //还有另一种形式QFileDialog::List，这个只是把文件的文件名以列表的形式显示出来
    fileDialog->setGeometry(10,30,300,200);//设置文件对话框的显示位置
    fileDialog->setDirectory(".");//设置文件对话框打开时初始打开的位置
    QStringList filters;
    filters << "Text files (*.txt)";
    fileDialog->setNameFilters(filters);
    if(fileDialog->exec() == QDialog::Accepted) {//注意使用的是QFileDialog::Accepted或者QDialog::Accepted,不是QFileDialog::Accept
        QString path = fileDialog->selectedFiles()[0];//得到用户选择的文件名
        qDebug()<<path<<endl;
        if(copyFileToPath(fileName,path,true)){
            qDebug()<<dbName+" copy YES!"<<endl;
            QMessageBox::information(this,"提示","保存成功");
        }else{
            QMessageBox::critical(this,"提示","保存失败");
        }
    }

}

void MainWindow::onRadioClick()
{
    QPalette redPalette;
    redPalette.setColor(QPalette::WindowText,Qt::red);
    QPalette grayPalette;
    grayPalette.setColor(QPalette::WindowText,Qt::gray);

    if (sender() == ui->radioButton){
        ui->stayDayEdit->setEnabled(true);
        ui->dateEdit_5->setEnabled(false);
        ui->radioButton->setPalette(redPalette);
        ui->radioButton_2->setPalette(grayPalette);
    }else if(sender() == ui->radioButton_2){
        ui->stayDayEdit->setEnabled(false);
        ui->dateEdit_5->setEnabled(true);
        ui->radioButton->setPalette(grayPalette);
        ui->radioButton_2->setPalette(redPalette);
    }
}

void MainWindow::comboBoxProcess(QString str)
{
    //验证输入项 是否存在
    QComboBox *senderBox = qobject_cast< QComboBox *>(sender());
    int boxIndex = senderBox->findText(str,Qt::MatchContains);
    if(boxIndex<0)
    {
        senderBox->setCurrentIndex(0);
    }
}

void MainWindow::categoryProcess(int index)
{
    if (sender() == ui->comboBox_7)
    {
        qDebug()<<index<<endl;
        ui->comboBox_13->clear();
        QString signTypeStr= ui->MainWindow::comboBox_7->currentText();
        QStringList strlist=signTypeStr.split(" ");
        QPalette redPalette;
        redPalette.setColor(QPalette::WindowText,Qt::red);
        QPalette blackPalette;
        blackPalette.setColor(QPalette::WindowText,Qt::black);
        QPalette grayPalette;
        grayPalette.setColor(QPalette::WindowText,Qt::gray);

        QSqlDatabase db = QSqlDatabase::database("wconntosqlite",true);
        QString dbName = ui->groupBox_3->title();
        dbName =  dbName.replace(0,3,"");
        QString dirStr = qApp->applicationDirPath()+"/data/"+dbName;
        QDir dir;
        if(!dir.exists(dirStr))//判断需要创建的文件夹是否存在
        {
            dir.mkdir(dirStr); //创建文件夹
        }

        db.setDatabaseName(dirStr+"/"+dbName+".db");
        if (db.open()){

            QSqlQuery query(db);
            if(strlist[0]=='T'){
                //团号
                ui->groupNum1Edit->setText(ui->groupEdit->text());
                ui->label_69->setPalette(redPalette);
                //职业
                //                ui->label_35->setPalette(redPalette);
                //                ui->comboBox_6->setEnabled(true);
                //                {
                //                    QStringList career;
                //                    QString careerSqlStr= QLatin1String("select key,value from career");
                //                    if (!query.prepare(careerSqlStr))
                //                    {
                //                        qDebug()<< query.lastError();
                //                    }
                //                    query.exec();
                //                    while (query.next()) {
                //                        QString key = query.value(0).toString();
                //                        QString value = query.value(1).toString();
                //                        career<< key + " " + value;
                //                        qDebug() << key << value;
                //                    }
                //                    ui->comboBox_6->addItems(career);
                //                }
                //团体人数
                ui->label_34->setPalette(redPalette);
                ui->totalNumEdit->setEnabled(true);
                //入境口岸
                ui->label_58->setPalette(grayPalette);
                ui->comboBox_14->setEnabled(false);
                ui->comboBox_14->clear();
                //接待社
                ui->label_64->setPalette(redPalette);
                ui->label_67->setPalette(redPalette);
                ui->comboBox_11->setEnabled(true);
                ui->comboBox_12->setEnabled(true);
                /*接待*/
                {
                    QStringList receiver;
                    QString receiverSqlStr= QLatin1String("select value from Receiver");
                    if (!query.prepare(receiverSqlStr))
                    {
                        qDebug()<< query.lastError();
                    }
                    query.exec();
                    while (query.next()) {
                        QString key = query.value(0).toString();

                        DesCrypt *des = new DesCrypt();
                        QString qKey = "lixiaomi";
                        char *qCharKey = qKey.toLatin1().data();
                        des->setKey(qCharKey);
                        des->decrypt(key.toLatin1().data());
                        QString dedata = QString::fromLocal8Bit(des->dedata.c_str());
                        QByteArray tempArray = QByteArray::fromBase64(dedata.toLocal8Bit());
                        receiver<< QString(tempArray);
                        qDebug() << key;
                    }
                    ui->comboBox_11->addItems(receiver);
                }
                /*接待人*/
                {
                    QStringList receiverContact;
                    QString receiverContactSqlStr= QLatin1String("select key,value from Receivercontact");
                    if (!query.prepare(receiverContactSqlStr))
                    {
                        qDebug()<< query.lastError();
                    }
                    query.exec();
                    while (query.next()) {
                        QString key = query.value(0).toString();
                        QString value = query.value(1).toString();

                        DesCrypt *des = new DesCrypt();
                        QString qKey = "lixiaomi";
                        char *qCharKey = qKey.toLatin1().data();
                        des->setKey(qCharKey);
                        des->decrypt(key.toLatin1().data());
                        QString dedata = QString::fromLocal8Bit(des->dedata.c_str());
                        QByteArray tempArray = QByteArray::fromBase64(dedata.toLocal8Bit());

                        //                        DesCrypt *des1 = new DesCrypt();
                        //                        des1->setKey(qCharKey);
                        //                        des1->decrypt(value.toLatin1().data());
                        //                        QString dedata1 = QString::fromLocal8Bit(des1->dedata.c_str());
                        //                        QByteArray tempArray1 = QByteArray::fromBase64(dedata1.toLocal8Bit());

                        receiverContact<< QString(tempArray) + " " + value;
                    }
                    ui->comboBox_12->addItems(receiverContact);
                }
                //当签证种类为T团体签证时。入境事由则自动转为：05旅游
                ui->comboBox_9->setCurrentIndex(4);
            }else{
                //团号
                ui->groupNum1Edit->clear();
                ui->label_69->setPalette(grayPalette);
                //职业
                //                ui->label_35->setPalette(grayPalette);
                //                ui->comboBox_6->setEnabled(false);
                //                ui->comboBox_6->clear();
                //团体人数
                ui->label_34->setPalette(grayPalette);
                ui->totalNumEdit->clear();
                ui->totalNumEdit->setEnabled(false);
                //入境口岸
                ui->label_58->setPalette(redPalette);
                ui->label_58->setEnabled(true);
                ui->comboBox_14->setEnabled(true);
                {
                    QStringList import;
                    QString importSqlStr= QLatin1String("select key,value from Import");
                    if (!query.prepare(importSqlStr))
                    {
                        qDebug()<< query.lastError();
                    }
                    query.exec();
                    while (query.next()) {
                        QString key = query.value(0).toString();
                        QString value = query.value(1).toString();
                        import<< key + " " + value;
                        qDebug() << key << value;
                    }
                    ui->comboBox_14->addItems(import);
                    //入境口岸默认为罗湖
                    ui->comboBox_14->setCurrentIndex(3);
                }
                //接待社
                ui->label_64->setPalette(grayPalette);
                ui->label_67->setPalette(grayPalette);
                ui->comboBox_11->setEnabled(false);
                ui->comboBox_12->setEnabled(false);
                ui->comboBox_11->clear();
                ui->comboBox_12->clear();

                //当签证种类为非（T团体签证）时。入境事由则自动转为：99旅游
                ui->comboBox_9->setCurrentIndex(16);

            }

            //待定
            if(strlist[0]=='O'||strlist[0]=='m'){
                ui->comboBox_10->setCurrentIndex(0);
            }else{
                ui->comboBox_10->setCurrentIndex(0);
            }
            ui->comboBox_13->blockSignals(true);

            /*申请详细类别*/
            {
                QStringList category;
                QString sqlStr= "select key,value from Category where signtype = '"+ strlist[0] +"'";
                if (!query.prepare(sqlStr))
                {
                    //qDebug()<< query.lastError();
                }
                query.exec();
                while (query.next()) {
                    QString key = query.value(0).toString();
                    QString value = query.value(1).toString();
                    category<< key + " " + value;
                }
                ui->comboBox_13->addItems(category);
                //签证种类默认为O S2(短期私人事务) 申请详细类别自动变为20237041
                if(strlist[0]=='O'){
                    ui->comboBox_13->setCurrentIndex(3);
                }else if(strlist[0]=='m'){
                    //当签证种类为m(贸易签证) 申请详细类别自动变为20235021
                    ui->comboBox_13->setCurrentIndex(1);
                }
            }
        }
        db.close();
        ui->comboBox_13->blockSignals(false);
    }

}

void MainWindow::firstNameEditFinish()
{
    QString nameStr = ui->firstNameEdit->text();
    ui->firstNameEdit->setText(nameStr.toUpper());

    QString signTypeStr= ui->MainWindow::comboBox_7->currentText();
    QStringList strlist=signTypeStr.split(" ");
    //团号
    if(strlist[0]=='T'){
        ui->groupNum1Edit->setText(ui->groupEdit->text());
    }else{
        ui->groupNum1Edit->clear();
    }
}

void MainWindow::lastNameEditFinish()
{
    QString nameStr = ui->lastNameEdit->text();
    ui->lastNameEdit->setText(nameStr.toUpper());
}

void MainWindow::photoNameEditFinish()
{
    QString nameStr = ui->groupEdit->text() + ui->numEdit->text()+"A.jpg";
    ui->photoEdit->setText(nameStr);

    QString signTypeStr= ui->MainWindow::comboBox_7->currentText();
    QStringList strlist=signTypeStr.split(" ");
    //团号
    if(strlist[0]=='T'){
        ui->groupNum1Edit->setText(ui->groupEdit->text());
    }else{
        ui->groupNum1Edit->clear();
    }
}

void MainWindow::currentModelIndex(const QModelIndex &index)
{
    QSqlRecord record = model->record(index.row());

    ui->groupEdit->setText(record.value("groupnum").toString());
    ui->numEdit->setText(record.value("num").toString());
    ui->firstNameEdit->setText(record.value("firstname").toString());
    ui->lastNameEdit->setText(record.value("lastname").toString());
    ui->chtNameEdit->setText(record.value("name").toString());
    ui->certNumEdit->setText(record.value("cert").toString());
    ui->destinationEdit->setText(record.value("destination").toString());
    ui->totalNumEdit->setText(record.value("totalnum").toString());
    ui->stayDayEdit->setText(record.value("stayday").toString());
    ui->certAddressEdit_2->setText(record.value("certaddress").toString());
    ui->groupNum1Edit->setText(record.value("groupnum1").toString());
    ui->agentNumEdit->setText(record.value("agentnum").toString());
    ui->agentEdit->setText(record.value("agent").toString());
    ui->inviteNumEdit->setText(record.value("invitenum").toString());
    ui->inviteEdit->setText(record.value("invite").toString());
    ui->photoEdit->setText(record.value("photo").toString());
    ui->companyEdit->setText(record.value("company").toString());

    //性别
    int sexIndex = ui->comboBox_2->findText(record.value("sexy").toString(),Qt::MatchContains);
    ui->comboBox_2->setCurrentIndex(sexIndex);

    int docTypeIndex = ui->comboBox->findText(record.value("docType").toString(),Qt::MatchContains);
    ui->comboBox->setCurrentIndex(docTypeIndex);

    int burnIndex = ui->comboBox_3->findText(record.value("burn").toString(),Qt::MatchContains);
    ui->comboBox_3->setCurrentIndex(burnIndex);

    int nationIndex = ui->comboBox_4->findText(record.value("nationality").toString(),Qt::MatchContains);
    ui->comboBox_4->setCurrentIndex(nationIndex);

    int certTypeIndex = ui->comboBox_5->findText(record.value("certtype").toString(),Qt::MatchContains);
    ui->comboBox_5->setCurrentIndex(certTypeIndex);

    int careerIndex = ui->comboBox_6->findText(record.value("career").toString(),Qt::MatchContains);
    ui->comboBox_6->setCurrentIndex(careerIndex);

    int signTypeIndex = ui->comboBox_7->findText(record.value("signtype").toString(),Qt::MatchContains);
    ui->comboBox_7->setCurrentIndex(signTypeIndex);

    int signTimeIndex = ui->comboBox_8->findText(record.value("signtime").toString(),Qt::MatchContains);
    ui->comboBox_8->setCurrentIndex(signTimeIndex);

    int reasonIndex = ui->comboBox_9->findText(record.value("reason").toString(),Qt::MatchContains);
    ui->comboBox_9->setCurrentIndex(reasonIndex);

    if(record.value("carrysign").toString().isEmpty()){
        ui->comboBox_10->setCurrentIndex(-1);
    }else{
        int carrySignIndex = ui->comboBox_10->findText(record.value("carrysign").toString(),Qt::MatchContains);
        ui->comboBox_10->setCurrentIndex(carrySignIndex);
    }

    int receiverIndex = ui->comboBox_11->findText(record.value("receiver").toString(),Qt::MatchContains);
    ui->comboBox_11->setCurrentIndex(receiverIndex);

    int receiverContactIndex = ui->comboBox_12->findText(record.value("receivercontact").toString(),Qt::MatchContains);
    ui->comboBox_12->setCurrentIndex(receiverContactIndex);

    int categoryIndex = ui->comboBox_13->findText(record.value("category").toString(),Qt::MatchContains);
    ui->comboBox_13->setCurrentIndex(categoryIndex);

    int importIndex = ui->comboBox_14->findText(record.value("import").toString(),Qt::MatchContains);
    ui->comboBox_14->setCurrentIndex(importIndex);

    //出生日期
    ui->dateEdit->setDate(QDate::fromString(record.value("birthday").toString(),"yyyyMMdd"));
    //证件签发日期
    ui->dateEdit_4->setDate(QDate::fromString(record.value("certissuedate").toString(),"yyyyMMdd"));
    //证件有效日期
    ui->dateEdit_2->setDate(QDate::fromString(record.value("certexpirydate").toString(),"yyyyMMdd"));
    //签证有效期
    ui->dateEdit_3->setDate(QDate::fromString(record.value("signdate").toString(),"yyyyMMdd"));
    //本次停留期
    ui->dateEdit_5->setDate(QDate::fromString(record.value("staydate").toString(),"yyyyMMdd"));

}

void MainWindow::showError(const QSqlError &err)
{
    QMessageBox::critical(this, "Unable to initialize Database",
                          "Error initializing database: " + err.text());
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::loadTableDataSource()
{
    QSqlDatabase db = QSqlDatabase::database("wconntosqlite",true);
    QString dbName = ui->groupBox_3->title();
    dbName =  dbName.replace(0,3,"");
    QString dirStr = qApp->applicationDirPath()+"/data/"+dbName;
    QDir dir;
    if(!dir.exists(dirStr))//判断需要创建的文件夹是否存在
    {
        dir.mkdir(dirStr); //创建文件夹
    }

    db.setDatabaseName(dirStr+"/"+dbName+".db");
    if (db.open()){
        QStringList tables = db.tables();
        // Create the data model
        model = new QSqlRelationalTableModel(ui->applyTable,db);
        model->setEditStrategy(QSqlTableModel::OnManualSubmit);
        model->setTable("ApplyForm");

        model->setHeaderData(model->fieldIndex("docType"), Qt::Horizontal, tr("材料级别"));
        model->setHeaderData(model->fieldIndex("groupnum"), Qt::Horizontal, tr("团号"));
        model->setHeaderData(model->fieldIndex("num"), Qt::Horizontal, tr("证件序号"));
        model->setHeaderData(model->fieldIndex("name"), Qt::Horizontal, tr("中文姓名"));
        model->setHeaderData(model->fieldIndex("lastname"), Qt::Horizontal, tr("英文姓"));

        model->setHeaderData(model->fieldIndex("firstname"), Qt::Horizontal, tr("英文名"));
        model->setHeaderData(model->fieldIndex("nationality"), Qt::Horizontal, tr("国籍"));
        model->setHeaderData(model->fieldIndex("sexy"), Qt::Horizontal, tr("性别"));
        model->setHeaderData(model->fieldIndex("birthday"), Qt::Horizontal, tr("出生日期"));
        model->setHeaderData(model->fieldIndex("burn"), Qt::Horizontal, tr("出生地"));

        model->setHeaderData(model->fieldIndex("certtype"), Qt::Horizontal, tr("证件种类"));
        model->setHeaderData(model->fieldIndex("cert"), Qt::Horizontal, tr("证件号码"));
        model->setHeaderData(model->fieldIndex("certexpirydate"), Qt::Horizontal, tr("证件有效期"));
        model->setHeaderData(model->fieldIndex("certissuedate"), Qt::Horizontal, tr("证件签发日期"));
        model->setHeaderData(model->fieldIndex("certaddress"), Qt::Horizontal, tr("证件出生地"));

        model->setHeaderData(model->fieldIndex("career"), Qt::Horizontal, tr("职业"));
        model->setHeaderData(model->fieldIndex("totalnum"), Qt::Horizontal, tr("团队人数"));
        model->setHeaderData(model->fieldIndex("destination"), Qt::Horizontal, tr("前往地点"));
        model->setHeaderData(model->fieldIndex("signtype"), Qt::Horizontal, tr("签证种类"));
        model->setHeaderData(model->fieldIndex("signtime"), Qt::Horizontal, tr("签证有效次数"));

        model->setHeaderData(model->fieldIndex("signdate"), Qt::Horizontal, tr("签证有效期"));
        model->setHeaderData(model->fieldIndex("reason"), Qt::Horizontal, tr("入境事由"));
        model->setHeaderData(model->fieldIndex("invitenum"), Qt::Horizontal, tr("邀请单位代码"));
        model->setHeaderData(model->fieldIndex("invite"), Qt::Horizontal, tr("邀请单位名称"));
        model->setHeaderData(model->fieldIndex("agentnum"), Qt::Horizontal, tr("代办单位代码"));

        model->setHeaderData(model->fieldIndex("agent"), Qt::Horizontal, tr("代办单位名称"));
        model->setHeaderData(model->fieldIndex("receiver"), Qt::Horizontal, tr("接待社名称"));
        model->setHeaderData(model->fieldIndex("receivercontact"), Qt::Horizontal, tr("接待社联系方式"));
        model->setHeaderData(model->fieldIndex("category"), Qt::Horizontal, tr("申请详细类别"));
        model->setHeaderData(model->fieldIndex("stayday"), Qt::Horizontal, tr("本次停留期"));

        model->setHeaderData(model->fieldIndex("staydate"), Qt::Horizontal, tr("本次停留期至"));
        model->setHeaderData(model->fieldIndex("import"), Qt::Horizontal, tr("拟入境口岸"));
        model->setHeaderData(model->fieldIndex("carrysign"), Qt::Horizontal, tr("携行标识"));
        model->setHeaderData(model->fieldIndex("photo"), Qt::Horizontal, tr("照片文件名"));
        model->setHeaderData(model->fieldIndex("groupnum1"), Qt::Horizontal, tr("团号"));
        // Populate the model
        if (!model->select()) {
            qDebug()<<"ddddd";
            showError(model->lastError());
            return;
        }

        // Set the model and hide the ID column
        ui->applyTable->setModel(model);
        ui->applyTable->setColumnHidden(model->fieldIndex("id"), true);
        ui->applyTable->setSelectionMode(QAbstractItemView::SingleSelection);
        // Initialize the Author combo box
        ui->applyTable->setCurrentIndex(model->index(0, 0));
        db.close();
    }
}

void MainWindow::rightGroupBox()
{
    connect(ui->newPushBtn, SIGNAL(clicked()), this, SLOT(newPushAction()));
    connect(ui->leadIntoPushBtn, SIGNAL(clicked()), this, SLOT(leadIntoAction()));
    connect(ui->prePushBtn, SIGNAL(clicked()), this, SLOT(prePushAction()));
    connect(ui->nextPushBtn, SIGNAL(clicked()), this, SLOT(nextPushAction()));
    connect(ui->addPushBtn, SIGNAL(clicked()), this, SLOT(addPushAction()));
    connect(ui->editPushBtn, SIGNAL(clicked()), this, SLOT(editPushAction()));
    connect(ui->delPushBtn, SIGNAL(clicked()), this, SLOT(delPushAction()));
    connect(ui->quitPushBtn, SIGNAL(clicked()), this, SLOT(quitPushAction()));
    connect(ui->savePushBtn, SIGNAL(clicked()), this, SLOT(saveAction()));
    connect(ui->cancelSavePushBtn, SIGNAL(clicked()), this, SLOT(cancelSaveAction()));
    connect(ui->sortPushBtn, SIGNAL(clicked()), this, SLOT(sortPushAction()));

    connect(ui->pushButton_13, SIGNAL(clicked()), this, SLOT(createApply()));
    connect(ui->pushButton_14, SIGNAL(clicked()), this, SLOT(printer1Action()));
    connect(ui->pushButton_15, SIGNAL(clicked()), this, SLOT(printer2Action()));
    connect(ui->pushButton_16, SIGNAL(clicked()), this, SLOT(printer3Action()));

}

bool isDirExist(QString fullPath)
{
    QDir dir(fullPath);
    if(dir.exists())
    {
        return true;
    }
    else
    {
        bool ok = dir.mkdir(fullPath);//只创建一级子目录，即必须保证上级目录存在
        return ok;
    }
}

void MainWindow::printer1Action()
{
    QString fileName;
    QFile pdfFile("aa.pdf");
    pdfFile.open(QIODevice::WriteOnly);                 // 打开要写入的pdf文件
    QPdfWriter* pPdfWriter = new QPdfWriter(&pdfFile);  // 创建pdf写入器
    pPdfWriter->setPageSize(QPagedPaintDevice::A4);     // 设置纸张为A4
    pPdfWriter->setResolution(300);                     // 设置纸张的分辨率为300,因此其像素为3508X2479

    int iMargin = 60;                   // 页边距
    pPdfWriter->setPageMargins(QMarginsF(iMargin, iMargin, iMargin, iMargin));

    QPainter* pPdfPainter = new QPainter(pPdfWriter);   // qt绘制工具

    // 标题,居中
    QTextOption option(Qt::AlignHCenter | Qt::AlignVCenter);
    option.setWrapMode(QTextOption::WordWrap);

    // 标题上边留白
    int iTop = 100;

    // 文本宽度2100
    int iContentWidth = 2100;

    // 标题,22号字
    QFont font;
    font.setFamily("simhei.ttf");
    int fontSize = 22;
    font.setPointSize(fontSize);
    pPdfPainter->setFont(font);                    // 为绘制工具设置字体
    pPdfPainter->drawText(QRect(0, iTop, iContentWidth, 90),
        QString::fromLocal8Bit("我的标题我骄傲"), option);

    // 内容,16号字，左对齐
    fontSize = 16;
    font.setPointSize(fontSize);
    pPdfPainter->setFont(font);
    option.setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    iTop += 60;
    pPdfPainter->drawText(QRect(0, iTop, iContentWidth, 60),
        QString::fromLocal8Bit("1、目录一"));
    iTop += 60;
    // 左侧缩进2字符
    int iLeft = 120;
    pPdfPainter->drawText(QRect(iLeft, iTop, iContentWidth - iLeft, 60),
        QString::fromLocal8Bit("我的目录一的内容。"), option);
    iTop += 60;
    pPdfPainter->drawText(QRect(0, iTop, iContentWidth, 60), QString::fromLocal8Bit("2、目录二"));
    iTop += 60;
    pPdfPainter->drawText(QRect(iLeft, iTop, iContentWidth - iLeft, 60),
        QString::fromLocal8Bit("我的目录一的内容"), option);

    delete pPdfPainter;
    delete pPdfWriter;
    pdfFile.close();
}


void MainWindow::printer2Action()
{
    PrinterDialog *priterDialog = new PrinterDialog(); //数据导入过滤界面
    if(priterDialog->exec()==QDialog::Accepted){

    }else{

    }
}


void MainWindow::printer3Action()
{

}

void insertAAA(QSqlQuery &q)
{
    QString insertSqlStr = QLatin1String("insert into Nation(key, value ) values(?, ?)");

    if (!q.prepare(insertSqlStr))
    {
        qDebug()<< q.lastError();
    }

    QFile file( ":/file/Nation" );
    if(!file.exists()){
        qDebug()<<"the file not exist!"<<endl;
    }
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug()<<"Can't open the file!"<<endl;
    }
    while(!file.atEnd()) {
        QByteArray line = file.readLine();
        QString str(line);
        qDebug()<<str<<endl;
        str.replace(QString("\r"), QString("\n"));
        str.replace(QString("\n"), QString(""));
        str.replace(QString("\t"), QString(" "));
        QStringList strlist=str.split(" ");
        q.addBindValue(strlist[0]);
        q.addBindValue(strlist[1]);
        q.exec();
        qDebug()<<strlist[0]<<strlist[1];
    }
    file.close();
    return;
    QString insertSqlStr2 = QLatin1String("select * from Burn");

    if (!q.prepare(insertSqlStr2))
    {
        qDebug()<< q.lastError();
    }
    q.exec();
    while (q.next()) {
        QString key = q.value(0).toString();
        QString value = q.value(1).toString();
        qDebug() << key << value;
    }
}

void insertBurn(QSqlQuery &q)
{
    QString insertSqlStr = QLatin1String("insert into Burn(key, value ) values(?, ?)");

    if (!q.prepare(insertSqlStr))
    {
        qDebug()<< q.lastError();
    }

    QFile file( ":/file/Burn" );
    if(!file.exists()){
        qDebug()<<"the file not exist!"<<endl;
    }
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug()<<"Can't open the file!"<<endl;
    }
    while(!file.atEnd()) {
        QByteArray line = file.readLine();
        QString str(line);
        str.replace(QString("\r"), QString("\n"));
        str.replace(QString("\n"), QString(""));
        str.replace(QString("\t"), QString(" "));
        QStringList strlist=str.split(" ");
        q.addBindValue(strlist[0]);
        q.addBindValue(strlist[1]);
        q.exec();
        qDebug()<<strlist[0]<<strlist[1];
    }
    file.close();
}

void insertCareer(QSqlQuery &q)
{
    QString insertSqlStr = QLatin1String("insert into Career(key, value ) values(?, ?)");

    if (!q.prepare(insertSqlStr))
    {
        qDebug()<< q.lastError();
    }

    QFile file( ":/file/Career" );
    if(!file.exists()){
        qDebug()<<"the file not exist!"<<endl;
    }
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug()<<"Can't open the file!"<<endl;
    }
    while(!file.atEnd()) {
        QByteArray line = file.readLine();
        QString str(line);
        str.replace(QString("\r"), QString("\n"));
        str.replace(QString("\n"), QString(""));
        str.replace(QString("\t"), QString(" "));
        QStringList strlist=str.split(" ");
        q.addBindValue(strlist[0]);
        q.addBindValue(strlist[1]);
        q.exec();
        qDebug()<<strlist[0]<<strlist[1];
    }
    file.close();
}

void insertCarrySign(QSqlQuery &q)
{
    QString insertSqlStr = QLatin1String("insert into CarrySign(key, value ) values(?, ?)");

    if (!q.prepare(insertSqlStr))
    {
        qDebug()<< q.lastError();
    }

    QFile file( ":/file/CarrySign" );
    if(!file.exists()){
        qDebug()<<"the file not exist!"<<endl;
    }
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug()<<"Can't open the file!"<<endl;
    }
    while(!file.atEnd()) {
        QByteArray line = file.readLine();
        QString str(line);
        str.replace(QString("\r"), QString("\n"));
        str.replace(QString("\n"), QString(""));
        str.replace(QString("\t"), QString(" "));
        QStringList strlist=str.split(" ");
        q.addBindValue(strlist[0]);
        q.addBindValue(strlist[1]);
        q.exec();
        qDebug()<<strlist[0]<<strlist[1];
    }
    file.close();
}

void insertCert(QSqlQuery &q)
{
    QString insertSqlStr = QLatin1String("insert into Cert(key, value ) values(?, ?)");

    if (!q.prepare(insertSqlStr))
    {
        qDebug()<< q.lastError();
    }

    QFile file( ":/file/Cert" );
    if(!file.exists()){
        qDebug()<<"the file not exist!"<<endl;
    }
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug()<<"Can't open the file!"<<endl;
    }
    while(!file.atEnd()) {
        QByteArray line = file.readLine();
        QString str(line);
        str.replace(QString("\r"), QString("\n"));
        str.replace(QString("\n"), QString(""));
        str.replace(QString("\t"), QString(" "));
        QStringList strlist=str.split(" ");
        q.addBindValue(strlist[0]);
        q.addBindValue(strlist[1]);
        q.exec();
        qDebug()<<strlist[0]<<strlist[1];
    }
    file.close();
}

void insertReason(QSqlQuery &q)
{
    QString insertSqlStr = QLatin1String("insert into Reason(key, value ) values(?, ?)");

    if (!q.prepare(insertSqlStr))
    {
        qDebug()<< q.lastError();
    }

    QFile file( ":/file/Reason" );
    if(!file.exists()){
        qDebug()<<"the file not exist!"<<endl;
    }
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug()<<"Can't open the file!"<<endl;
    }
    while(!file.atEnd()) {
        QByteArray line = file.readLine();
        QString str(line);
        str.replace(QString("\r"), QString("\n"));
        str.replace(QString("\n"), QString(""));
        str.replace(QString("\t"), QString(" "));
        QStringList strlist=str.split(" ");
        q.addBindValue(strlist[0]);
        q.addBindValue(strlist[1]);
        q.exec();
        qDebug()<<strlist[0]<<strlist[1];
    }
    file.close();
}

void insertSignTime(QSqlQuery &q)
{
    QString insertSqlStr = QLatin1String("insert into SignTime(key, value ) values(?, ?)");

    if (!q.prepare(insertSqlStr))
    {
        qDebug()<< q.lastError();
    }

    QFile file( ":/file/SignTime" );
    if(!file.exists()){
        qDebug()<<"the file not exist!"<<endl;
    }
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug()<<"Can't open the file!"<<endl;
    }
    while(!file.atEnd()) {
        QByteArray line = file.readLine();
        QString str(line);
        str.replace(QString("\r"), QString("\n"));
        str.replace(QString("\n"), QString(""));
        str.replace(QString("\t"), QString(" "));
        QStringList strlist=str.split(" ");
        q.addBindValue(strlist[0]);
        q.addBindValue(strlist[1]);
        q.exec();
        qDebug()<<strlist[0]<<strlist[1];
    }
    file.close();
}

void insertSignType(QSqlQuery &q)
{
    QString insertSqlStr = QLatin1String("insert into SignType(key, value ) values(?, ?)");

    if (!q.prepare(insertSqlStr))
    {
        qDebug()<< q.lastError();
    }

    QFile file( ":/file/SignType" );
    if(!file.exists()){
        qDebug()<<"the file not exist!"<<endl;
    }
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug()<<"Can't open the file!"<<endl;
    }
    while(!file.atEnd()) {
        QByteArray line = file.readLine();
        QString str(line);
        str.replace(QString("\r"), QString("\n"));
        str.replace(QString("\n"), QString(""));
        str.replace(QString("\t"), QString(" "));
        QStringList strlist=str.split(" ");
        q.addBindValue(strlist[0]);
        q.addBindValue(strlist[1]);
        q.exec();
        qDebug()<<strlist[0]<<strlist[1];
    }
    file.close();
}

void insertSexy(QSqlQuery &q)
{
    QString insertSqlStr = QLatin1String("insert into Sexy(key, value ) values(?, ?)");

    if (!q.prepare(insertSqlStr))
    {
        qDebug()<< q.lastError();
    }

    QFile file( ":/file/Sexy" );
    if(!file.exists()){
        qDebug()<<"the file not exist!"<<endl;
    }
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug()<<"Can't open the file!"<<endl;
    }
    while(!file.atEnd()) {
        QByteArray line = file.readLine();
        QString str(line);
        str.replace(QString("\r"), QString("\n"));
        str.replace(QString("\n"), QString(""));
        str.replace(QString("\t"), QString(" "));
        QStringList strlist=str.split(" ");
        q.addBindValue(strlist[0]);
        q.addBindValue(strlist[1]);
        q.exec();
        qDebug()<<strlist[0]<<strlist[1];
    }
    file.close();
}

void insertDocType(QSqlQuery &q)
{
    QString insertSqlStr = QLatin1String("insert into DocType(key, value ) values(?, ?)");

    if (!q.prepare(insertSqlStr))
    {
        qDebug()<< q.lastError();
    }

    QFile file( ":/file/DocType" );
    if(!file.exists()){
        qDebug()<<"the file not exist!"<<endl;
    }
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug()<<"Can't open the file!"<<endl;
    }
    while(!file.atEnd()) {
        QByteArray line = file.readLine();
        QString str(line);
        str.replace(QString("\r"), QString("\n"));
        str.replace(QString("\n"), QString(""));
        str.replace(QString("\t"), QString(" "));
        QStringList strlist=str.split(" ");
        q.addBindValue(strlist[0]);
        q.addBindValue(strlist[1]);
        q.exec();
        qDebug()<<strlist[0]<<strlist[1];
    }
    file.close();
}

void insertCategory(QSqlQuery &q)
{
    QString insertSqlStr = QLatin1String("insert into Category(key,signtype, value ) values(?,?, ?)");

    if (!q.prepare(insertSqlStr))
    {
        qDebug()<< q.lastError();
    }

    QFile file( ":/file/Category" );
    if(!file.exists()){
        qDebug()<<"the file not exist!"<<endl;
    }
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug()<<"Can't open the file!"<<endl;
    }
    while(!file.atEnd()) {
        QByteArray line = file.readLine();
        QString str(line);
        str.replace(QString("\r"), QString("\n"));
        str.replace(QString("\n"), QString(""));
        str.replace(QString("\t"), QString(" "));
        QStringList strlist=str.split(" ");
        q.addBindValue(strlist[0]);
        q.addBindValue(strlist[1]);
        q.addBindValue(strlist[2]);
        q.exec();
        qDebug()<<strlist[0]<<strlist[1];
    }
    file.close();
}
/*
 * @brief 设置捆号
 */
void MainWindow::setPackage(QString package)
{
    QString packageStr = "捆号:" + package  ;
    ui->groupBox_3->setTitle(packageStr);

    ui->savePushBtn->setEnabled(false);
    ui->cancelSavePushBtn->setEnabled(false);
    ui->groupBox_2->setEnabled(false);

    /*sql 操作*/
    if (!QSqlDatabase::drivers().contains("QSQLITE"))
        QMessageBox::critical(this, "Unable to load database", "This demo needs the SQLITE driver");

    // initialize the database
    QSqlDatabase mydb=QSqlDatabase::addDatabase("QSQLITE","wconntosqlite");
    QString dirStr = qApp->applicationDirPath()+"/data/"+package;
    QDir dir;
    if(!dir.exists(dirStr))//判断需要创建的文件夹是否存在
    {
        dir.mkdir(dirStr); //创建文件夹
    }

    mydb.setDatabaseName(dirStr+"/"+package+".db");
    if (!mydb.open()){
        qDebug()<<"not open";
    }else{
        QStringList tables = mydb.tables();
        //        QSqlQuery q(mydb);
        //        insertAAA(q);
        //        insertBurn(q);
        //        insertCareer(q);
        //        insertCarrySign(q);
        //        insertCert(q);
        //        insertReason(q);
        //        insertSignTime(q);
        //        insertSignType(q);
        //        insertDocType(q);
        //        insertSexy(q);
        //        insertCategory(q);

        // Create the data model
        model = new QSqlRelationalTableModel(ui->applyTable,mydb);
        model->setEditStrategy(QSqlTableModel::OnManualSubmit);
        model->setTable("ApplyForm");

        // Set the relations to the other database tables

        model->setHeaderData(model->fieldIndex("docType"), Qt::Horizontal, tr("材料级别"));
        model->setHeaderData(model->fieldIndex("groupnum"), Qt::Horizontal, tr("团号"));
        model->setHeaderData(model->fieldIndex("num"), Qt::Horizontal, tr("证件序号"));
        model->setHeaderData(model->fieldIndex("name"), Qt::Horizontal, tr("中文姓名"));
        model->setHeaderData(model->fieldIndex("lastname"), Qt::Horizontal, tr("英文姓"));

        model->setHeaderData(model->fieldIndex("firstname"), Qt::Horizontal, tr("英文名"));
        model->setHeaderData(model->fieldIndex("nationality"), Qt::Horizontal, tr("国籍"));
        model->setHeaderData(model->fieldIndex("sexy"), Qt::Horizontal, tr("性别"));
        model->setHeaderData(model->fieldIndex("birthday"), Qt::Horizontal, tr("出生日期"));
        model->setHeaderData(model->fieldIndex("burn"), Qt::Horizontal, tr("出生地"));

        model->setHeaderData(model->fieldIndex("certtype"), Qt::Horizontal, tr("证件种类"));
        model->setHeaderData(model->fieldIndex("cert"), Qt::Horizontal, tr("证件号码"));
        model->setHeaderData(model->fieldIndex("certexpirydate"), Qt::Horizontal, tr("证件有效期"));
        model->setHeaderData(model->fieldIndex("certissuedate"), Qt::Horizontal, tr("证件签发日期"));
        model->setHeaderData(model->fieldIndex("certaddress"), Qt::Horizontal, tr("证件出生地"));

        model->setHeaderData(model->fieldIndex("career"), Qt::Horizontal, tr("职业"));
        model->setHeaderData(model->fieldIndex("totalnum"), Qt::Horizontal, tr("团队人数"));
        model->setHeaderData(model->fieldIndex("destination"), Qt::Horizontal, tr("前往地点"));
        model->setHeaderData(model->fieldIndex("signtype"), Qt::Horizontal, tr("签证种类"));
        model->setHeaderData(model->fieldIndex("signtime"), Qt::Horizontal, tr("签证有效次数"));

        model->setHeaderData(model->fieldIndex("signdate"), Qt::Horizontal, tr("签证有效期"));
        model->setHeaderData(model->fieldIndex("reason"), Qt::Horizontal, tr("入境事由"));
        model->setHeaderData(model->fieldIndex("invitenum"), Qt::Horizontal, tr("邀请单位代码"));
        model->setHeaderData(model->fieldIndex("invite"), Qt::Horizontal, tr("邀请单位名称"));
        model->setHeaderData(model->fieldIndex("agentnum"), Qt::Horizontal, tr("代办单位代码"));

        model->setHeaderData(model->fieldIndex("agent"), Qt::Horizontal, tr("代办单位名称"));
        model->setHeaderData(model->fieldIndex("receiver"), Qt::Horizontal, tr("接待社名称"));
        model->setHeaderData(model->fieldIndex("receivercontact"), Qt::Horizontal, tr("接待社联系方式"));
        model->setHeaderData(model->fieldIndex("category"), Qt::Horizontal, tr("申请详细类别"));
        model->setHeaderData(model->fieldIndex("stayday"), Qt::Horizontal, tr("本次停留期"));

        model->setHeaderData(model->fieldIndex("staydate"), Qt::Horizontal, tr("本次停留期至"));
        model->setHeaderData(model->fieldIndex("import"), Qt::Horizontal, tr("拟入境口岸"));
        model->setHeaderData(model->fieldIndex("carrysign"), Qt::Horizontal, tr("携行标识"));
        model->setHeaderData(model->fieldIndex("photo"), Qt::Horizontal, tr("照片文件名"));
        model->setHeaderData(model->fieldIndex("groupnum1"), Qt::Horizontal, tr("团号"));
        model->setHeaderData(model->fieldIndex("company"), Qt::Horizontal, tr("公司编号"));

        // Populate the model
        if (!model->select()) {
            showError(model->lastError());
            return;
        }

        // Set the model and hide the ID column
        ui->applyTable->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
        ui->applyTable->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);
        ui->applyTable->horizontalHeader()->setMinimumSectionSize(100);

        ui->applyTable->setModel(model);
        ui->applyTable->setColumnHidden(model->fieldIndex("id"), true);
        ui->applyTable->setSelectionMode(QAbstractItemView::SingleSelection);

        // Initialize the Author combo box
        ui->applyTable->setCurrentIndex(model->index(0, 0));
        connect(ui->applyTable,SIGNAL(clicked(QModelIndex)),this,SLOT(currentModelIndex(QModelIndex)));

        QSqlQuery query(mydb);
        /*普通 急办*/
        {
            QStringList docType;
            QString docTypeStr= QLatin1String("select key,value from DocType");
            if (!query.prepare(docTypeStr))
            {
                qDebug()<< query.lastError();
            }
            query.exec();
            while (query.next()) {
                QString key = query.value(0).toString();
                QString value = query.value(1).toString();
                docType<< key + " " + value;
            }
            ui->comboBox->addItems(docType);
            //默认为1加急
            ui->comboBox->setCurrentIndex(1);
        }

        /*性别*/
        {
            QStringList sexy;
            QString sexyStr= QLatin1String("select key,value from Sexy");
            if (!query.prepare(sexyStr))
            {
                qDebug()<< query.lastError();
            }
            query.exec();
            while (query.next()) {
                QString key = query.value(0).toString();
                QString value = query.value(1).toString();
                sexy<< key + " " + value;
            }
            ui->comboBox_2->addItems(sexy);
        }

        /*出生地*/
        {
            QStringList burn;
            QString burnSqlStr= QLatin1String("select key,value from Burn");
            if (!query.prepare(burnSqlStr))
            {
                qDebug()<< query.lastError();
            }
            query.exec();
            while (query.next()) {
                QString key = query.value(0).toString();
                QString value = query.value(1).toString();
                burn<< key + " " + value;
            }
            ui->comboBox_3->addItems(burn);
        }

        /*国籍*/
        {
            QStringList nation;
            QString nationSqlStr= QLatin1String("select key,value from Nation");
            if (!query.prepare(nationSqlStr))
            {
                qDebug()<< query.lastError();
            }
            query.exec();
            while (query.next()) {
                QString key = query.value(0).toString();
                QString value = query.value(1).toString();
                nation<< key + " " + value;
            }
            ui->comboBox_4->addItems(nation);
        }

        /*证件种类*/
        {
            QStringList cert;
            QString certSqlStr= QLatin1String("select key,value from Cert");
            if (!query.prepare(certSqlStr))
            {
                qDebug()<< query.lastError();
            }
            query.exec();
            while (query.next()) {
                QString key = query.value(0).toString();
                QString value = query.value(1).toString();
                cert<< key + " " + value;
            }
            ui->comboBox_5->addItems(cert);
            //证件种类默认为普通护照
            ui->comboBox_5->setCurrentIndex(3);
        }

        /*签证种类*/
        {
            QStringList signType;
            QString signTypeSqlStr= QLatin1String("select key,value from SignType");
            if (!query.prepare(signTypeSqlStr))
            {
                qDebug()<< query.lastError();
            }
            query.exec();
            while (query.next()) {
                QString key = query.value(0).toString();
                QString value = query.value(1).toString();
                signType<< key + " " + value;
                //                qDebug() << key << value;
            }
            ui->comboBox_7->addItems(signType);
            //签证种类默认为O 短期私人事务签证(S2
            ui->comboBox_7->setCurrentIndex(3);
            connect(ui->comboBox_7, SIGNAL(currentIndexChanged(int)), this, SLOT(categoryProcess(int)));
        }

        /*有效次数*/
        {
            QStringList signTime;
            QString signTimeSqlStr= QLatin1String("select key,value from SignTime");
            if (!query.prepare(signTimeSqlStr))
            {
                qDebug()<< query.lastError();
            }
            query.exec();
            while (query.next()) {
                QString key = query.value(0).toString();
                QString value = query.value(1).toString();
                signTime<< key + " " + value;
                //                qDebug() << key << value;
            }
            ui->comboBox_8->addItems(signTime);
            //有效次数默认为一次出入境
            ui->comboBox_8->setCurrentIndex(1);
        }

        /*入境事由*/
        {
            QStringList reason;
            QString reasonSqlStr= QLatin1String("select key,value from Reason");
            if (!query.prepare(reasonSqlStr))
            {
                qDebug()<< query.lastError();
            }
            query.exec();
            while (query.next()) {
                QString key = query.value(0).toString();
                QString value = query.value(1).toString();
                reason<< key + " " + value;
                //                qDebug() << key << value;
            }
            ui->comboBox_9->addItems(reason);
            //入境事由默认为99其他
            ui->comboBox_9->setCurrentIndex(16);
        }

        /*携行标识*/
        {
            QStringList carrySign;
            QString carrySignSqlStr= QLatin1String("select key,value from CarrySign");
            if (!query.prepare(carrySignSqlStr))
            {
                qDebug()<< query.lastError();
            }
            query.exec();
            while (query.next()) {
                QString key = query.value(0).toString();
                QString value = query.value(1).toString();
                carrySign<< key + " " + value;
                //                qDebug() << key << value;
            }
            ui->comboBox_10->addItems(carrySign);
            ui->comboBox_10->setCurrentIndex(-1);
        }

        {
            QStringList career;
            QString careerSqlStr= QLatin1String("select key,value from career");
            if (!query.prepare(careerSqlStr))
            {
                qDebug()<< query.lastError();
            }
            query.exec();
            while (query.next()) {
                QString key = query.value(0).toString();
                QString value = query.value(1).toString();
                career<< key + " " + value;
                qDebug() << key << value;
            }
            ui->comboBox_6->addItems(career);
            //职业默认为40 职员
            ui->comboBox_6->setCurrentIndex(39);
        }
        mydb.close();
    }

    /*待办单位代码、待办单位名称、邀请单位代码、邀请单位名称、照片文件名*/
    {
        ui->agentNumEdit->setText("SDL");
        ui->agentEdit->setText("山东(香港)旅行社有限公司");

        ui->inviteNumEdit->setText("SDDWMYIHZ");
        ui->inviteEdit->setText("山东省对外贸易经济合作厅");

        ui->photoEdit->setText("");
    }
    //QPushButton 点击事件
    rightGroupBox();
    emit  ui->comboBox_7->currentIndexChanged(0);

}

/*
 * @brief 新建
 */
void MainWindow::newPushAction()
{
    //what you want to do
    this->close();
    qApp->exit( 888 );
}

/*
 * @brief 导入
 */
void MainWindow::leadIntoAction()
{
    //what you want to do
    QFileDialog *fileDialog = new QFileDialog(this);//创建一个QFileDialog对象，构造函数中的参数可以有所添加。
    fileDialog->setWindowTitle(tr("Open As"));//设置文件保存对话框的标题
    fileDialog->setAcceptMode(QFileDialog::AcceptOpen);//设置文件对话框为保存模式
    fileDialog->setFileMode(QFileDialog::AnyFile);//设置文件对话框弹出的时候显示任何文件，不论是文件夹还是文件
    fileDialog->setViewMode(QFileDialog::Detail);//文件以详细的形式显示，显示文件名，大小，创建日期等信息；

    //还有另一种形式QFileDialog::List，这个只是把文件的文件名以列表的形式显示出来
    fileDialog->setGeometry(10,30,300,200);//设置文件对话框的显示位置
    fileDialog->setDirectory(".");//设置文件对话框打开时初始打开的位置
    QStringList filters;
    filters << "Text files (*.txt)";
    fileDialog->setNameFilters(filters);
    if(fileDialog->exec() == QDialog::Accepted) {//注意使用的是QFileDialog::Accepted或者QDialog::Accepted,不是QFileDialog::Accept
        QString filePath = fileDialog->selectedFiles()[0];//得到用户选择的文件名
        qDebug()<<filePath<<endl;
        QStringList lines;
        QFile file( filePath );
        //    QTextCodec::setCodecForLocale(QTextCodec::codecForName("gb2312"));//中文转码声明
        if ( file.open( QIODevice::ReadOnly ) ) {//只读方式
            QTextStream stream( &file );
            QString line;
            int n = 1;
            while ( !stream.atEnd() ) {
                line = stream.readLine(); // 一行一行读取，不包括“/n”的一行文本，也可以用readAll()全部读取
                line.replace(QString("\t"), QString("|"));
                qDebug()<< line; //输出到“应用程序输出”窗口。
                n++;
                lines += line;
            }

            DataFilterDialog *dataDialog = new DataFilterDialog(lines); //数据导入过滤界面
            if(dataDialog->exec()==QDialog::Accepted){
                qDebug()<<dataDialog->resultSourceList<<endl;

                insertData(dataDialog->resultSourceList);
            }else{

            }

            file.close();
        }else{
            qDebug()<< "line.toUtf8()"<<endl; //输出到“应用程序输出”窗口。
        }

    }
}
/*
 * @brief 上一个
 */
void MainWindow::prePushAction()
{
    //what you want to do
    QModelIndex aModel = ui->applyTable->currentIndex();
    int row = aModel.row();
    if(row==0||model->rowCount()==0)
        return;
    row--;
    ui->applyTable->selectRow(row);
    QModelIndex bModel = model->index(row,aModel.column());
    emit  ui->applyTable->clicked(bModel);
}

/*
 * @brief 下一个
 */
void MainWindow::nextPushAction()
{
    //what you want to do
    QModelIndex aModel = ui->applyTable->currentIndex();
    int row = aModel.row();
    if(row==model->rowCount()-1)
        return;
    row++;
    ui->applyTable->selectRow(row);
    QModelIndex bModel = model->index(row,aModel.column());
    emit  ui->applyTable->clicked(bModel);
}

/*
 * @brief 增加
 */
void MainWindow::addPushAction()
{
    isUpdate = false;
    //what you want to do
    ui->groupBox_3->setEnabled(false);
    ui->groupBox_2->setEnabled(true);
    ui->applyTable->setEnabled(false);
    ui->newPushBtn->setDisabled(true);
    ui->prePushBtn->setEnabled(false);
    ui->nextPushBtn->setEnabled(false);
    ui->addPushBtn->setEnabled(false);
    ui->quitPushBtn->setEnabled(false);
    ui->editPushBtn->setEnabled(false);
    ui->delPushBtn->setEnabled(false);

    ui->leadIntoPushBtn->setEnabled(true);
    ui->savePushBtn->setEnabled(true);
    ui->cancelSavePushBtn->setEnabled(true);
    ui->sortPushBtn->setEnabled(true);
    ui->groupBox_3->setEnabled(true);

    /*增加、查询数据库最后一条数据 作缓存用*/
    if(model->rowCount()!=0){
        //序号自增
        QModelIndex bModel = model->index(model->rowCount()-1,0);
        emit  ui->applyTable->clicked(bModel);
        ui->comboBox->setCurrentIndex(1);
        ui->comboBox_5->setCurrentIndex(3);
        ui->comboBox_6->setCurrentIndex(39);
        ui->comboBox_7->setCurrentIndex(3);
        ui->comboBox_8->setCurrentIndex(1);
        ui->comboBox_9->setCurrentIndex(16);
        ui->comboBox_10->setCurrentIndex(-1);

        QSqlRecord record = model->record(model->rowCount()-1);

        int signTypeIndex = ui->comboBox_7->findText(record.value("signtype").toString(),Qt::MatchContains);
        //团签
        if(signTypeIndex == 6){
            qlonglong number = record.value("num").toLongLong();
            number++;
            QString numberStr = QString::number(number, 10);
            ui->numEdit->setText(numberStr);
            ui->dateEdit_3->setDate(QDate::currentDate().addDays(15));

        }else{
            qlonglong num = record.value("groupnum").toLongLong();
            num++;
            QString numStr = QString::number(num, 10);
            ui->groupEdit->setText(numStr);

            ui->numEdit->setText("1");
            ui->dateEdit_3->setDate(QDate::currentDate().addDays(5));
        }

        ui->firstNameEdit->clear();
        ui->lastNameEdit->clear();
        ui->chtNameEdit->clear();
        ui->certAddressEdit_2->clear();
        ui->certNumEdit->clear();

        ui->dateEdit->setDate(QDate::currentDate());
        ui->dateEdit_2->setDate(QDate::currentDate());
        ui->dateEdit_4->setDate(QDate::currentDate());
        ui->dateEdit_5->setDate(QDate::currentDate());

        emit  ui->groupEdit->editingFinished();
    }else{
        ui->numEdit->setText("1");
        ui->comboBox_5->setCurrentIndex(3);

    }
    /*主动更新页面数据*/
    repaint();
}

/*
 * @brief 保存
 */
void MainWindow::saveAction()
{
    ui->applyTable->setEnabled(true);

    QSqlDatabase db = QSqlDatabase::database("wconntosqlite",true);

    QString dbName = ui->groupBox_3->title();
    dbName =  dbName.replace(0,3,"");
    QString dirStr = qApp->applicationDirPath()+"/data/"+dbName;
    QDir dir;
    if(!dir.exists(dirStr))//判断需要创建的文件夹是否存在
    {
        dir.mkdir(dirStr); //创建文件夹
    }

    db.setDatabaseName(dirStr+"/"+dbName+".db");
    if (db.open()){
        QSqlQuery q(db);
        QString insertSqlStr = "";

        if(isUpdate){
            QString aa = "update ApplyForm set groupnum = ?,docType=?,num=?,firstname=?,lastname=?,name=?,";
            QString bb = "sexy=?,birthday=?,burn=?,nationality=?,certtype=?,cert=?,";
            QString cc = "certissuedate=?,certexpirydate=?,company=?,career=?,destination=?,totalnum=?,";
            QString dd = "signtype=?,signtime=?,signdate=?,reason=?,carrysign=?,category=?,";
            QString ee = "stayday=?,staydate=?,import=?,certaddress=?,groupnum1=?,agentnum=?,";
            QString ff = "agent=?,invitenum=?,invite=?,receiver=?,receivercontact=?,photo=? where id = ?";
            insertSqlStr = aa+bb+cc+dd+ee+ff;
        }else{
            QString aa = "insert into ApplyForm(groupnum,docType,num,firstname,lastname,name,";
            QString bb = "sexy,birthday,burn,nationality,certtype,cert,";
            QString cc = "certissuedate,certexpirydate,company,career,destination,totalnum,";
            QString dd = "signtype,signtime,signdate,reason,carrysign,category,";
            QString ee = "stayday,staydate,import,certaddress,groupnum1,agentnum,";
            QString ff = "agent,invitenum,invite,receiver,receivercontact,photo)";
            QString gg = "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            insertSqlStr = aa+bb+cc+dd+ee+ff+gg;
        }

        if (!q.prepare(insertSqlStr))
        {
            qDebug()<< q.lastError();
        }

        {
            //团号 非空
            QString groupStr= ui->MainWindow::groupEdit->text();
            if(groupStr.length()!=15){
                QMessageBox::critical(this,"提示","请输入15位团号/委托书号");
                return;
            }
            q.addBindValue(groupStr);
        }

        {
            //普办/急办
            QString docTypeStr= ui->MainWindow::comboBox->currentText();
            if(docTypeStr.isEmpty()){
                QMessageBox::critical(this,"提示","请选择普办/急办");
                return;
            }
            QStringList strlist=docTypeStr.split(" ");
            q.addBindValue(strlist[0]);
        }

        {
            //捆号中的序号
            QString numStr= ui->MainWindow::numEdit->text();
            if(numStr.toInt()<=0||numStr.toInt()>1000){
                QMessageBox::critical(this,"提示","请输入0-999以内序号");
                return;
            }
            q.addBindValue(numStr);
        }

        {
            //英文名
            QString firstnameStr= ui->MainWindow::firstNameEdit->text();
            if(firstnameStr.length()<0||firstnameStr.length()>30){
                QMessageBox::critical(this,"提示","请输入30位以内英文名");
                return;
            }
            q.addBindValue(firstnameStr);
        }

        {
            //英文姓
            QString lastnameStr= ui->MainWindow::lastNameEdit->text();
            if(lastnameStr.length()<=0||lastnameStr.length()>20){
                QMessageBox::critical(this,"提示","请输入20位以内英文姓");
                return;
            }
            q.addBindValue(lastnameStr);
        }

        {
            //中文名
            QString chtnameStr= ui->MainWindow::chtNameEdit->text();
            if(chtnameStr.length()<0||chtnameStr.length()>24){
                QMessageBox::critical(this,"提示","请输入24位以内中文名");
                return;
            }
            q.addBindValue(chtnameStr);
        }

        {
            //性别
            QString sexStr= ui->MainWindow::comboBox_2->currentText();
            if(sexStr.isEmpty()){
                QMessageBox::critical(this,"提示","请选择性别");
                return;
            }
            QStringList strlist=sexStr.split(" ");
            q.addBindValue(strlist[0]);
        }

        {
            //生日
            QDate date= ui->MainWindow::dateEdit->date();
            q.addBindValue(date.toString("yyyyMMdd"));
        }

        {
            //出生地
            QString burnStr= ui->MainWindow::comboBox_3->currentText();
            QStringList strlist=burnStr.split(" ");
            q.addBindValue(strlist[0]);
        }

        {
            //国籍
            QString nationStr= ui->MainWindow::comboBox_4->currentText();
            if(nationStr.isEmpty()){
                QMessageBox::critical(this,"提示","请选择国籍");
                return;
            }
            QStringList strlist=nationStr.split(" ");
            q.addBindValue(strlist[0]);
        }

        {
            //证件类型
            //所持证件种类	2	非空，字典903	偕行儿童的所持证件种类与父母的一致
            QString certTypeStr= ui->MainWindow::comboBox_5->currentText();
            if(certTypeStr.isEmpty()){
                QMessageBox::critical(this,"提示","请选择证件类型");
                return;
            }
            QStringList strlist=certTypeStr.split(" ");
            q.addBindValue(strlist[0]);
        }

        {
            //证件
            //所持证件号码	20	"非空，对普通签证来说是所持证件号码 对团体签证来说是团员的护照号码"	偕行儿童的所持证件号码与父母的证号一致
            QString certStr= ui->MainWindow::certNumEdit->text();
            if(certStr.length()>20){
                QMessageBox::critical(this,"提示","请输入20位以内证件");
                return;
            }
            q.addBindValue(certStr);
        }

        {
            //证件签发日期
            //非空，yyyymmdd
            QDate date= ui->MainWindow::dateEdit_4->date();
            q.addBindValue(date.toString("yyyyMMdd"));
        }

        {
            //证件有效日期
            //非空，yyyymmdd
            QDate date= ui->MainWindow::dateEdit_2->date();
            q.addBindValue(date.toString("yyyyMMdd"));
        }

        {
            //公司编号
            QString companyStr= ui->MainWindow::companyEdit->text();
            q.addBindValue(companyStr);
        }

        {
            //职业
            //字典103
            QString careerStr= ui->MainWindow::comboBox_6->currentText();
            if(careerStr.isEmpty()){
                QMessageBox::critical(this,"提示","请选择职业");
                return;
            }
            QStringList strlist=careerStr.split(" ");
            q.addBindValue(strlist[0]);
        }

        {
            //前往地点
            //汉字（带空格和代码）
            QString destinationStr= ui->MainWindow::destinationEdit->text();
            if(destinationStr.length()>5){
                QMessageBox::critical(this,"提示","请输入5位地点");
                return;
            }
            q.addBindValue(destinationStr);
        }

        {
            //成员人数
            //数字3位	只有团体签证才有值，并且非空
            QString totalNumStr= ui->MainWindow::totalNumEdit->text();
            QString signTypeStr= ui->MainWindow::comboBox_7->currentText();
            QStringList strlist1=signTypeStr.split(" ");
            //团号
            if(strlist1[0]=='T'){
                if(totalNumStr.toInt()<0||totalNumStr.toInt()>1000){
                    QMessageBox::critical(this,"提示","请输入0~999位以内人数");
                    return;
                }
                q.addBindValue(totalNumStr);
            }else{
                q.addBindValue("");
            }
        }

        //签证种类
        //"字典206，一般情况下直接入库；为T是团体签证"
        QString signTypeStr= ui->MainWindow::comboBox_7->currentText();
        if(signTypeStr.isEmpty()){
            QMessageBox::critical(this,"提示","请选择签证种类");
            return;
        }
        QStringList signTypelist=signTypeStr.split(" ");
        q.addBindValue(signTypelist[0]);

        {
            //有效次数
            QString signTimeStr= ui->MainWindow::comboBox_8->currentText();
            if(signTimeStr.isEmpty()){
                QMessageBox::critical(this,"提示","请选择有效次数");
                return;
            }
            QStringList strlist=signTimeStr.split(" ");
            q.addBindValue(strlist[0]);
        }

        {
            //签证有效期
            QDate date= ui->MainWindow::dateEdit_3->date();
            qDebug()<<date.toString("yyyyMMdd")<<endl;
            q.addBindValue(date.toString("yyyyMMdd"));
        }

        {
            //入境理由
            QString reasonStr= ui->MainWindow::comboBox_9->currentText();
            QStringList strlist=reasonStr.split(" ");
            q.addBindValue(strlist[0]);
        }

        {
            //偕行标识
            QString carrySignStr= ui->MainWindow::comboBox_10->currentText();
            QStringList strlist=carrySignStr.split(" ");
            q.addBindValue(strlist[0]);
        }

        {
            //详细类别
            QString categoryStr= ui->MainWindow::comboBox_13->currentText();
            QStringList strlist=categoryStr.split(" ");
            q.addBindValue(strlist[0]);
        }

        {
            //3		"非空，本次入境停留天数，（不超过30），与“本次停留期至”二选一。"
            if (ui->radioButton->isChecked()){
                QString stayDayStr= ui->MainWindow::stayDayEdit->text();
                if(stayDayStr.toInt()>30){
                    QMessageBox::critical(this,"提示","本次入境停留天数不超过30");
                    return;
                }
                q.addBindValue(stayDayStr);
            }else{
                q.addBindValue("");
            }
        }

        {
            //本次停留期
            if (ui->radioButton_2->isChecked()){
                QDate date= ui->MainWindow::dateEdit_5->date();
                qDebug()<<date.toString("yyyyMMdd")<<endl;
                q.addBindValue(date.toString("yyyyMMdd"));
            }else{
                q.addBindValue("");
            }
        }

        {
            //入境口岸 12	字典881，只有普通签证才有，并且非空
            if(signTypelist[0]=='T'){
                q.addBindValue("");
            }else{
                QString importStr= ui->MainWindow::comboBox_14->currentText();
                QStringList strlist=importStr.split(" ");
                q.addBindValue(strlist[0]);
            }
        }

        {
            //100	证件上的英文出生地	非空
            QString certAddressStr= ui->MainWindow::certAddressEdit_2->text();
            if(certAddressStr.length()>100||certAddressStr.length()<=0){
                QMessageBox::critical(this,"提示","请输入100位以内证件出生地地点");
                return;
            }
            q.addBindValue(certAddressStr);
        }

        {
            //团号 非空
            if(signTypelist[0]=='T'){
                QString groupStr= ui->MainWindow::groupNum1Edit->text();
                if(groupStr.length()!=15){
                    QMessageBox::critical(this,"提示","请输入15位团号/委托书号");
                    return;
                }
                q.addBindValue(groupStr);
            }else{
                q.addBindValue("");
            }
        }

        {
            //10	使用原代办旅行社代码	非空，可以3或4位
            QString agentnum= ui->MainWindow::agentNumEdit->text();
            if(agentnum.length()>4||agentnum.length()<3){
                QMessageBox::critical(this,"提示","请输入3位或4位代办旅行社代码");
                return;
            }
            q.addBindValue(agentnum);
        }

        {
            //"代办旅行社名称，不入库，做代办单位代码校验时用"
            QString agentStr= ui->MainWindow::agentEdit->text();
            if(agentStr.length()>=40){
                QMessageBox::critical(this,"提示","请输入40位以内旅行社名称");
                return;
            }
            q.addBindValue(agentStr);
        }

        {
            //10	"一类单位代码（4或6位）；其它单位为9位组织机构代码"
            QString invitenum= ui->MainWindow::inviteNumEdit->text();
            if(invitenum.length()>10||invitenum.length()<0){
                QMessageBox::critical(this,"提示","请输入10位以内代码");
                return;
            }
            q.addBindValue(invitenum);
        }

        {
            //60	汉字
            QString inviteStr= ui->MainWindow::inviteEdit->text();
            if(inviteStr.length()>60){
                QMessageBox::critical(this,"提示","请输入60位以内中文邀请单位");
                return;
            }
            q.addBindValue(inviteStr);
        }

        //团号 非空
        if(signTypelist[0]=='T'){
            {
                //100	接待社名称，只有团体签证使用	团体签证必须录入
                QString receiver= ui->MainWindow::comboBox_11->currentText();
                if(receiver.length()>100||receiver.length()<0){
                    QMessageBox::critical(this,"提示","请输入100位以内接待社名称");
                    return;
                }
                q.addBindValue(receiver);
            }

            {
                //100	接待社联系人、联系电话，只有团体签证使用	团体签证必须录入
                QString receiverContact= ui->MainWindow::comboBox_12->currentText();
                if(receiverContact.length()>100||receiverContact.length()<0){
                    QMessageBox::critical(this,"提示","请输入100位以内接待社联系人、方式");
                    return;
                }
                q.addBindValue(receiverContact);
            }

        }else{
            q.addBindValue("");
            q.addBindValue("");
        }

        {
            //30	对应图像资料的文件名	"非空业务编号+序号+A.jpg"
            QString photoStr= ui->MainWindow::photoEdit->text();
            if(photoStr.length()>30||photoStr.length()<0){
                QMessageBox::critical(this,"提示","请输入30位以内图像资料的文件名式");
                return;
            }
            q.addBindValue(photoStr);
        }

        if(isUpdate){
            QModelIndex indexTemp = ui->applyTable->currentIndex();
            QSqlRecord record = model->record(indexTemp.row());
            qlonglong num = record.value("id").toLongLong();
            q.addBindValue(num);
        }
        if(q.exec()){
            loadTableDataSource();
            //保存成功,清除数据
            ui->newPushBtn->setEnabled(true);
            ui->prePushBtn->setEnabled(true);
            ui->nextPushBtn->setEnabled(true);
            ui->addPushBtn->setEnabled(true);
            ui->quitPushBtn->setEnabled(true);
            ui->editPushBtn->setEnabled(true);
            ui->delPushBtn->setEnabled(true);
            ui->leadIntoPushBtn->setEnabled(true);
            ui->sortPushBtn->setEnabled(true);

            ui->savePushBtn->setEnabled(false);
            ui->cancelSavePushBtn->setEnabled(false);

            bool isClearAll = true;
            //当前捆号没有记录则清空LineEditText
            if(isClearAll){
                ui->groupEdit->setText("");
                ui->numEdit->setText("");
                ui->lastNameEdit->setText("");
                ui->firstNameEdit->setText("");
                ui->chtNameEdit->setText("");
                ui->certNumEdit->setText("");
                ui->destinationEdit->setText("");
                ui->totalNumEdit->setText("");
            }

            /*清除currentIndex 选项*/
            QModelIndex bModel = model->index(-1,-1);
            ui->applyTable->setCurrentIndex(bModel);
            ui->applyTable->clearSelection();
        }else{
            QMessageBox::critical(this,"保存失败",q.lastError().text());
        }
    }else{
        QMessageBox::critical(this,"提示","打开db失败");
    }
    db.close();

}

void MainWindow::insertData(QStringList dataList)
{
    ui->applyTable->setEnabled(true);

    QSqlDatabase db = QSqlDatabase::database("wconntosqlite",true);
    QString dbName = ui->groupBox_3->title();
    dbName =  dbName.replace(0,3,"");
    QString dirStr = qApp->applicationDirPath()+"/data/"+dbName;
    QDir dir;
    if(!dir.exists(dirStr))//判断需要创建的文件夹是否存在
    {
        dir.mkdir(dirStr); //创建文件夹
    }

    db.setDatabaseName(dirStr+"/"+dbName+".db");
    if (db.open()){
        QSqlQuery q(db);
        QString aa = "insert into ApplyForm(docType,groupnum,num,name,lastname,firstname,";
        QString bb = "nationality,sexy,birthday,burn,certtype,cert,";
        QString cc = "certissuedate,certexpirydate,career,totalnum,destination,";
        QString dd = "signtype,signtime,signdate,reason,invitenum,invite,";
        QString ee = "agentnum,agent,carrysign,photo,category,stayday,staydate,";
        QString ff = "receiver,receivercontact,import,certaddress,groupnum1)";
        QString gg = "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        QString insertSqlStr = aa+bb+cc+dd+ee+ff+gg;

        if (!q.prepare(insertSqlStr))
        {
            qDebug()<< q.lastError();
        }
        bool isOK = false;
        foreach (QString index, dataList)
        {
            QStringList list1 = index.split("|");
            qDebug()<<list1<<endl;
            if(list1.length()!=35){
                qDebug()<<"=============="<<endl;
                continue;
            }
            int i=0;
            QStringList aaa;
            foreach (QString str, list1){
                q.addBindValue(str);
                qDebug()<<str<<endl;
                i++;
            }
            isOK = q.exec();
        }

        if(isOK){
            loadTableDataSource();
            //保存成功,清除数据
            ui->newPushBtn->setEnabled(true);
            ui->prePushBtn->setEnabled(true);
            ui->nextPushBtn->setEnabled(true);
            ui->addPushBtn->setEnabled(true);
            ui->quitPushBtn->setEnabled(true);
            ui->editPushBtn->setEnabled(true);
            ui->delPushBtn->setEnabled(true);
            ui->leadIntoPushBtn->setEnabled(true);
            ui->sortPushBtn->setEnabled(true);

            ui->savePushBtn->setEnabled(false);
            ui->cancelSavePushBtn->setEnabled(false);

            bool isClearAll = true;
            //当前捆号没有记录则清空LineEditText
            if(isClearAll){
                ui->groupEdit->setText("");
                ui->numEdit->setText("");
                ui->lastNameEdit->setText("");
                ui->firstNameEdit->setText("");
                ui->chtNameEdit->setText("");
                ui->certNumEdit->setText("");
                ui->destinationEdit->setText("");
                ui->totalNumEdit->setText("");
            }

            /*清除currentIndex 选项*/
            QModelIndex bModel = model->index(-1,-1);
            ui->applyTable->setCurrentIndex(bModel);
            ui->applyTable->clearSelection();
        }else{
            QMessageBox::critical(this,"导入失败","失败，请检查数据完整性，以及是否已存在该团号");
        }
    }else{
        QMessageBox::critical(this,"提示","打开db失败");
    }
    db.close();

}

/*
 * @brief 放弃保存
 */
void MainWindow::cancelSaveAction()
{
    QMessageBox::StandardButton rb = QMessageBox::question(NULL, "报盘", "确定放弃保存?", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
    if(rb == QMessageBox::Yes)
    {
        ui->applyTable->setEnabled(true);
        //what you want to do
        ui->newPushBtn->setEnabled(true);
        ui->prePushBtn->setEnabled(true);
        ui->nextPushBtn->setEnabled(true);
        ui->addPushBtn->setEnabled(true);
        ui->quitPushBtn->setEnabled(true);
        ui->editPushBtn->setEnabled(true);
        ui->delPushBtn->setEnabled(true);
        ui->leadIntoPushBtn->setEnabled(true);
        ui->sortPushBtn->setEnabled(true);

        ui->savePushBtn->setEnabled(false);
        ui->cancelSavePushBtn->setEnabled(false);

        bool isClearAll = true;
        //当前捆号没有记录则清空LineEditText
        if(isClearAll){
            ui->groupEdit->setText("");
            ui->numEdit->setText("");
            ui->lastNameEdit->setText("");
            ui->firstNameEdit->setText("");
            ui->chtNameEdit->setText("");
            ui->certNumEdit->setText("");
            ui->destinationEdit->setText("");
            ui->totalNumEdit->setText("");
        }
    }else if(rb == QMessageBox::No){

    }
}

void MainWindow::delPushAction()
{
    QMessageBox::StandardButton rb = QMessageBox::question(NULL, "报盘", "确定删除该记录?", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
    if(rb == QMessageBox::Yes)
    {
        QSqlDatabase db = QSqlDatabase::database("wconntosqlite",true);
        QString dbName = ui->groupBox_3->title();
        dbName =  dbName.replace(0,3,"");
        QString dirStr = qApp->applicationDirPath()+"/data/"+dbName;
        QDir dir;
        if(!dir.exists(dirStr))//判断需要创建的文件夹是否存在
        {
            dir.mkdir(dirStr); //创建文件夹
        }

        db.setDatabaseName(dirStr+"/"+dbName+".db");
        if (db.open()){
            QModelIndex aModel = ui->applyTable->currentIndex();
            model->removeRow(aModel.row());
            model->submitAll();
        }else{
            QMessageBox::critical(this,"提示","打开db失败");
        }
        db.close();
    }
}

void MainWindow::quitPushAction()
{
    QMessageBox::StandardButton rb = QMessageBox::question(NULL, "报盘", "确定退出吗?", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
    if(rb == QMessageBox::Yes)
    {
        qApp->exit( 0 );
    }
}

void MainWindow::editPushAction()
{
    QModelIndex indexTemp = ui->applyTable->currentIndex();
    QSqlRecord record = model->record(indexTemp.row());
    qlonglong num = record.value("groupnum").toLongLong();
    qDebug()<<num<<endl;
    if(num<=0){
        QMessageBox::critical(this,"提示","请先选择需要修改的数据");
        return;
    }
    isUpdate = true;
    ui->groupBox_3->setEnabled(false);
    ui->groupBox_2->setEnabled(true);
    ui->applyTable->setEnabled(false);
    ui->newPushBtn->setDisabled(true);
    ui->prePushBtn->setEnabled(false);
    ui->nextPushBtn->setEnabled(false);
    ui->addPushBtn->setEnabled(false);
    ui->quitPushBtn->setEnabled(false);
    ui->editPushBtn->setEnabled(false);
    ui->delPushBtn->setEnabled(false);

    ui->leadIntoPushBtn->setEnabled(true);
    ui->savePushBtn->setEnabled(true);
    ui->cancelSavePushBtn->setEnabled(true);
    ui->sortPushBtn->setEnabled(true);
    ui->groupBox_3->setEnabled(true);
}


void MainWindow::sortPushAction()
{
    QSqlDatabase db = QSqlDatabase::database("wconntosqlite",true);
    QString dbName = ui->groupBox_3->title();
    dbName =  dbName.replace(0,3,"");
    QString dirStr = qApp->applicationDirPath()+"/data/"+dbName;
    QDir dir;
    if(!dir.exists(dirStr))//判断需要创建的文件夹是否存在
    {
        dir.mkdir(dirStr); //创建文件夹
    }

    db.setDatabaseName(dirStr+"/"+dbName+".db");
    if (db.open()){
        QString numberStr = QString::number(isAscendingOrder, 10);
        qDebug()<<numberStr<<endl;
        this->isAscendingOrder = isAscendingOrder==1?2:1;
        QString numberStr2 = QString::number(isAscendingOrder, 10);
        qDebug()<<numberStr2<<endl;
        model->setSort(2,this->isAscendingOrder==1?Qt::AscendingOrder:Qt::DescendingOrder);
        model->select();
    }else{
        QMessageBox::critical(this,"提示","打开db失败");
    }
    db.close();
    repaint();
}

